package com.firewolf.solr.s06_mlk;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.junit.Before;
import org.junit.Test;

/**
 * MLT 组件
 * 
 * @author liuxing
 *
 */
public class MLTComponent {
	private HttpSolrClient client = null;

	@Before
	public void init() {
		// 获取solr连接，mycore1是集合名
		client = new HttpSolrClient("http://localhost:8081/solr/mycore3");
		System.out.println(client);
	}

	@Test
	public void mlt() throws Exception {
		SolrQuery q = new SolrQuery();
		q.setQuery("id:1004");// 需要被匹配的文档查询条件,一般使用ID唯一确定
		q.setParam("mlt", "true") // 开始相似搜索
				.setParam("mlt.fl", "name") // 需要判断相似度的域
				.setParam("mlt.mindf", "1") //
				.setParam("mlt.mintf", "1").setParam("mlt.count", String.valueOf(3));// 设置返回相似文章个数
		QueryResponse query = client.query(q);
		SimpleOrderedMap<?> so = (SimpleOrderedMap<?>) query.getResponse().get("moreLikeThis");
		for (int i = 0; i < so.size(); i++) {
			String name = so.getName(i); // 被匹配的数据主键，就是查询的那个id:1004
			System.out.println(name);
			SolrDocumentList sl = (SolrDocumentList) so.getVal(i);
			for (SolrDocument s : sl) {
				System.out.println(s);
			}
		}
	}

}
